import React, { Component,useState } from 'react'
import { UdPage, udConfigProvider, UdTable, IUdTableProps, IUdColumn,IUdDetailItem,UdDetail, columnRenders, http, UdModal} from '@/lib'
import { BackTop, message } from 'antd'
import { PaginationConfig } from 'antd/lib/table'
import apis from "@/apis/AboutQuota";
import Search from 'antd/lib/input/Search'
import "./style.scss";
import { Route } from 'react-router';
const updateBtnAuth = "quota_employee_manager_saveOrUpdateAssessSet";
const productGroup = JSON.parse(sessionStorage.getItem("productGroup"))
const brandCode = sessionStorage.getItem("brandCode");
var arr = []
class Apply extends Component<IQuotaValidityPeriodProps, IQuotaValidityPeriodState> {
  static resFieldKeys: {
    content: string,
    number: string
    numberOfElements: string
    size: string
    totalElements: string
    totalPages: string
  } = {
      content: 'content',
      number: 'number',
      numberOfElements: 'numberOfElements',
      size: 'size',
      totalElements: 'totalElements',
      totalPages: 'totalPages'
    }
  /** 滚动条容器 */
  protected pageContainer = udConfigProvider.ui.getPageContainer()
  private queryParams = {
    page: 1,
    size: 10,
  }
  constructor(props) {
    super(props)
    this.state = {
      querying: false,
      rowKey: 'groupName',
      pagination: { current: this.queryParams.page, pageSize: this.queryParams.size },
      tableProps: {},
      columns: [
        {
          title: "物料分类名称",
          key: "groupName",
          dataIndex: "groupName",
          minWidth: "120px",
        },
        {
          title: "当前动销/件",
          key: "nowMove",
          minWidth: "70px",
          render: (record) => (

            <a onClick={() => this.handeltoNextDetail(props,record)}>
              {record.nowMove}
            </a>
          ),
        },
        {
          title: "理论配额值/件",
          key: "quotaCountNum",
          dataIndex: "quotaCountNum",
          minWidth: "80px",
        },
        {
          title: "申请配额值/件",
          key: "quotaNum",
          dataIndex: "quotaNum",
          minWidth: "80px",
          render: (text, record) => {
            let value = record.quotaNum || ''
            return (
              <input
                placeholder="请输入"
                value={value}
                onChange={(e)=>this.guotaNum(this.state.dataSource,record,e)}
                min={0}
                style={{ width: 110 ,outline: 'none'}}
              />
            );
          },
        },
        {
          title: "配额有效期",
          key: "cycleEndTime",
          render: (text,record) => {
            function getYear(item){
              return item && item.substring(0,10)
            }
            let isShow = Boolean(record.cycleEndTime)
            return <span>
              <span className={isShow?'':'isShow'}>{getYear(record.cycleStartTime||'')+'~'+getYear(record.cycleEndTime||'')}</span>
              <span className={isShow?'isShow':''}>{''}</span>
              </span>
          },
          minWidth: "160px",
        },
        {
          title: "操作",
          dataIndex: "operate",
          fixedWidth: "80px",
          render: columnRenders.operate([
            {
              title: "移除",
              auth: updateBtnAuth,
              action: (text, record) => this.delList(this.state.dataSource,record,props),
            },
          ]),
        },
      ],
      detailItem: [
        {
          title: "客户名称",
          dataIndex: "dealerName",
          col: { span: 8 },
        },
        {
          title: "销售组织",
          dataIndex: "brandName",
          col: { span: 8 },
        },
        {
          title: "盘点周期",
          dataIndex: "inventoryCycle",
          col: { span: 6 },
        },
      ],
      dataSource: [],
      dataSourceDetail:[],
      qoutaTemplate: [],
      selectRoles:[],
      roleList:[]
    }
  }

  componentWillMount() {
    this.addApprover()
    this.getQuotaList()
  }
  render() {
    var props = this.props
    let style={display:'none'}
    return (
      <UdPage className="list-page">
        <Route>
          <div className="page-header">
            <div className="page-heading">
              <span className="page-heading-title">配额申请</span>
            </div>
            <div className="page-heading-extr" onClick={()=>this.goBack(props)}><a>返回</a></div>
          </div>
          <UdDetail items={this.state.detailItem} dataSource={this.state.dataSourceDetail}/>
          <UdTable loading={this.state.querying} rowKey={this.state.rowKey}
            pagination={this.state.pagination} {...this.state.tableProps}
            columns={this.state.columns} dataSource={this.state.dataSource}
            onChange={this.handleTableChange}
          />
          {this.pageContainer && <BackTop target={() => this.pageContainer} visibilityHeight={100} />}
        </Route>
        <section>
          <p className={this.state.qoutaTemplate.length ? 'maxTitle':'isShow'}>审批流程</p>
          {this.state.qoutaTemplate.map((item, index) => (
            <div className="approve" key={index}>
              <p className="leftSide">
                <span className="title"></span> {item.name}
              </p>
              <div className={item.userNames.length?"rightSide":'isShow'}>
                {item.userNames.map((items, indexs) => (
                  <div key={"vss" + indexs} className="nameLists">
                  <p className="approveName"  onClick={()=> this.getRoles(item,index)}>{items}</p>
                  <p>{items}</p>
                  </div>
                ))}
              </div>
              <div className={!item.userNames.length?"":'isShow rightSide'}>
                  <p className="approveName" onClick={()=> this.getRoles(item,index)}>+</p>
                  <p>选择审批人</p>
                  </div>
            </div>
          ))}
        </section>
        <button onClick={()=>this.submitApprove(this.state.dataSourceDetail,props)} className="submitBtn">提交审核</button>
      </UdPage>
    )
  }
  public goBack(props){
    props.history.goBack()
  }
  //申请配额修改
  public guotaNum(lists,record,e){
    lists.forEach( item => {
      if(item.productGroupId == record.productGroupId){
        item.quotaNum = Number(e.target.value)
      }
    })
    this.setState({dataSource:lists})
  }
  //获取列表数据
  public getQuotaList(){
    const productGroup = JSON.parse(sessionStorage.getItem("productGroup"))
    const dealerCode = JSON.parse(sessionStorage.getItem("dealerCode"))
      let productGroupIdList = []
      if(productGroup.length){
        productGroup.forEach(item=>{
          productGroupIdList.push(item.id)
        })
      }http.get(apis.GetProductGroupByDealer, {
        params: { brandCode:brandCode,dealerCode:dealerCode,productGroupIdList:productGroupIdList.join(',')},
      }).then(res=>{
        this.setState({
          dataSourceDetail: res.data,
          dataSource: res.data.quotaApplyDetailResps
        })
    })
  }
  //获取审批流程模板
  public addApprover(){
    var detailItem = JSON.parse(sessionStorage.getItem("checkItem"))
    const qoutaTemplates = JSON.parse(sessionStorage.getItem("qoutaTemplate"))
    this.setState({
      dataSourceDetail: detailItem
    })
    let selectRoles = []
    http.get(apis.getTemplate,{params:{brandCode:brandCode}}).then(res=>{
      res.data.forEach(item=>{
        item.userNames = item.userNames?item.userNames:[]
        item.userIds = []
        selectRoles.push({name:item.assignee,userIds:[]})
        sessionStorage.removeItem(item.name)
      })
      this.setState({
        qoutaTemplate: qoutaTemplates?qoutaTemplates:res.data,
        selectRoles:selectRoles
      })
      sessionStorage.removeItem("qoutaTemplate")
    })
  }
  //选择审批人
  public checkPoles(index){
    let lists = this.state.qoutaTemplate
    let lists2 = this.state.selectRoles
    let names = []
    let ids = []
    if(arr.length){
      arr.forEach(item=>{
        names.push(item.realName)
        ids.push(item.id)
        lists.forEach(items => {
            if(items.name == item.name){
              items.userNames = names
              items.userIds = ids
            }
            lists2.forEach(i=>{
              if(i.name == items.assignee){
                i.userIds = items.userIds
              }
            })
        });
      })
    }else {
      lists[index].userNames = []
      lists2[index].userIds = []
    }
    this.setState({
      qoutaTemplate: lists,
      roleList: arr,
      selectRoles:lists2
    })
  }
  //获取审批人
  public getRoles(item,index){
    let params = {ids: item.roles}
    let role = JSON.parse(sessionStorage.getItem(item.name))||[];
    arr = role?role:[]
    http.post(apis.GetRoleById,params).then(res=>{
      res.data.forEach(item=>{
        item.checked = false
        role&&role.forEach((items)=>{
          if(item.realName==items.realName && items.checked == true ){
            item.checked=true
          }
        })
      })
      this.setState({ roleList: res.data });
      UdModal.open({
        title: "选择审批人",
        content:<RolesList roleList={this.state.roleList} realName={item.name} items={item}/>,
        onOk: () => {
          this.checkPoles(index)
        },
      });
    })
  }
  //移除
  public delList = (list,row,props) => {
    list.forEach((item,index)=>{
      if(item.productGroupId==row.productGroupId){
        list.splice(index,1)
      }
    })
    productGroup.forEach((item,index)=>{
      if(item.id==row.productGroupId){
        productGroup.splice(index,1)
      }
    })
    sessionStorage.setItem('productGroup', JSON.stringify(productGroup))
    this.setState({dataSource: list})
    if(list.length<=0){
      props.history.goBack()
    }
  };
  public handleTableChange = (pagination, filters, sorter, extra) => {
    this.queryParams.page = pagination.current
    this.queryParams.size = pagination.pageSize
  }

  //动销明细
  public handeltoNextDetail = (props,row) => {
    sessionStorage.setItem('qoutaTemplate', JSON.stringify(this.state.qoutaTemplate))
    sessionStorage.setItem('productGroupId', JSON.stringify(row.productGroupId))
    sessionStorage.setItem('brandList',JSON.stringify(row))
    props.history.push({
      pathname: `/quota/qoutaapplyfor/detail`,
    }); 
  }
  // 提交审核
  public submitApprove(list,props){
    let {brandName,dealerCode,dealerName,inventoryCycle} = list
    list.quotaApplyDetailResps.forEach(item=>{
      item.quotaEndTime=item.cycleEndTime
      item.quotaStartTime=item.cycleStartTime
    })
    let params = {
      brandCode,
      brandName,
      dealerCode,
      dealerName,
      inventoryCycle,
      modifyType: "APPLYFOR",
      quotaApplyProductGroups: list.quotaApplyDetailResps,
      workflowReqVos: this.state.selectRoles
    }
    let user = []
    this.state.selectRoles.forEach(item=>{
      if(item.userIds.length){
        user.push(item)
      }
    })
    if(user.length>=this.state.selectRoles.length){
      http.post(apis.SaveOrUpdateQuota,params).then(res=>{
        if(res){
          message.success("申请成功!")
          setTimeout(()=>{
            props.history.goBack()
          },3000)
        }
      })
    }else if(user.length<this.state.selectRoles.length&&user.length>0){
      message.error('请选择节点审批人!')
    }else{
      message.error('请选择审批人!')
    }
  }
}

function checkroles(item,realName){
  item.name = realName
  item.checked = !item.checked
  /*如果有数据判断是不是一类，如果不是则添加，如果是同一类看是否是同一审批人，
  如果不是则添加,如果是同一个并且未选中，则去掉
  */
  if(arr.length){
    if(arr[0].name!=item.name){
      arr = []
      arr.push(item)
    }else{
      let flag = arr.every((i,idx)=>{
        return i.realName != item.realName
      })
      if(flag){
        if(item.checked){
          arr.push(item)
        }else{
          arr.forEach((i,idx)=>{
            if(i.realName == item.realName){
              arr.splice(idx,1)
            }
          })
        }
      }else{
        if(item.checked == false){
          arr.forEach((i,idx)=>{
            if(i.realName == item.realName){
              arr.splice(idx,1)
            }
          })
        }
      }
    }
  }else{
    arr.push(item)
  }
  sessionStorage.setItem(realName, JSON.stringify(arr))
}
//审批人列表
const RolesList = (props) => {
  const [realName, setRealName] = useState(props.realName)
  const [roleList, setRoleList] = useState(props.roleList)
  function getroleList(value,item){
    let params = {ids: item.roles,
      realName:value}
    http.post(apis.GetRoleById,params).then(res=>{
      res.data.forEach(item=>{
        item.checked = false
      })
      setRoleList(res.data)
    })
  }
  return <div>
    <Search
      placeholder="请输入"
      enterButton="搜索"
      onSearch={value => getroleList(value,props.items)}
    />
    <div className={roleList.length>0?'isShow':'sollor1'}>暂无审批人!</div>
    <div className={roleList.length<=0?'isShow':'sollor'}>
    {roleList.map((item,index)=>
    <div className="roleList" key={item.id}>
      <label key={index}>
        <input type="checkbox" defaultChecked={item.checked} onChange={() =>checkroles(item,realName)}/> {item.realName}
      </label>
    </div>
    )}
    </div>
  </div>
}

export default Apply

interface IQuotaValidityPeriodProps {
  tabs: any[]
}

interface IQuotaValidityPeriodState {
  querying: boolean
  rowKey: string | ((record: any, index: number) => string)
  pagination: PaginationConfig | false
  tableProps: IUdTableProps<any>
  columns: IUdColumn[]
  detailItem:IUdDetailItem[]
  dataSource: [],
  dataSourceDetail:any[]
  qoutaTemplate:any[],
  selectRoles:any[],
  roleList:any[]
  // currentBrand?: string
}
